package ar.fiuba.tp7552.buildadmin.webactions.gastos;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import ar.fiuba.tp7552.buildadmin.model.BusinessException;
import ar.fiuba.tp7552.buildadmin.model.builds.Edificio;
import ar.fiuba.tp7552.buildadmin.model.gastos.Gasto;
import ar.fiuba.tp7552.buildadmin.model.gastos.GastoReal;
import ar.fiuba.tp7552.buildadmin.model.gastos.Prevision;
import ar.fiuba.tp7552.buildadmin.model.gastos.TipoGasto;
import ar.fiuba.tp7552.buildadmin.service.EdificioService;
import ar.fiuba.tp7552.buildadmin.service.GastoService;
import ar.fiuba.tp7552.buildadmin.service.PermissionType;
import ar.fiuba.tp7552.buildadmin.webactions.BaseAction;

import com.opensymphony.xwork2.Preparable;

public class GastoAction extends BaseAction implements Preparable {
	
	private GastoService gastoService;
	private EdificioService edificioService;
	private GastoVO gasto = new GastoVO();
	private Map<Edificio, Collection<TipoGasto>>edificios;
	
	// ~~ Constructor ====================================================
	
	public GastoAction(GastoService gastoService, EdificioService edificioService) {
		super();
		this.gastoService = gastoService;
		this.edificioService = edificioService;
	}
	
	// ~~ Actions ========================================================
	
	@Override
	public void prepare() {
		Long id = gasto.getId();
		if ( id != null ) {
			Gasto g = gastoService.get(id);
			if (g instanceof Prevision) 
				gasto = new GastoVO((Prevision)g);
			else
				gasto = new GastoVO((GastoReal)g);
		}
	}
	
	public String  load() {
		return BaseAction.SUCCESS;
	}
	
	public String  delete() {
		gastoService.delete(gasto.get());
		return BaseAction.SUCCESS;
	}
	
	public String save() {
		try {
			Gasto entity = gasto.get();
			if (entity.isNew()) {
				gastoService.create(entity, BaseAction.getCurrentUser());
				gasto.setId(entity.getId());
			} else {
				gastoService.update(entity, BaseAction.getCurrentUser());
			}
			return BaseAction.SUCCESS;
		} catch (BusinessException e) {
			addActionError(e.getMessage());
			return BaseAction.INPUT;
		}
	}
	
	// ~~ getters y setters ========================================================
	
	public GastoVO getGasto() {
		return gasto;
	}

	public void setGasto(GastoVO gasto) {
		this.gasto = gasto;
	}

	public Map<Edificio, Collection<TipoGasto>> getEdificios() {
		if (edificios == null) {
			edificios = new LinkedHashMap<Edificio, Collection<TipoGasto>>();
			for (Edificio edificio : edificioService.getAll(PermissionType.GASTO)) {
				edificios.put(edificio, edificio.getTipoGastos());	
			}
		}
		return edificios;
	}
}